/**
 *       Copyright (c) 2012 Lukas Zaruba
 *
 *   This file is part of Robot Playground.
 *
 *   Robot Playground is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU Lesser General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   Robot Playground is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU Lesser General Public License for more details.
 *
 *   You should have received a copy of the GNU Lesser General Public License
 *   along with Robot Playground. If not, see <http://www.gnu.org/licenses/>.
 */
package net.zarubsys.commons.log4j.cfg;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map.Entry;
import java.util.Properties;

import org.eclipse.core.runtime.Platform;

/**
 * Based on loggin facility from Media Solutions Slovakia, a.s.
 * @author Lukas Zaruba, lukas.zaruba@gmail.com
 */
public class WorkspaceConfigProvider implements Log4JConfigProvider {

	public static final String PATTERN = "\\$\\[ws\\]";

	@Override
	public Properties getProperties() {
		String workspacePath = Platform.getInstanceLocation().getURL().getFile();
		File f = new File(workspacePath + "log4j.properties");
		Properties p = new Properties();
		if (!f.exists()) return p;
		System.out.println("Found additional Workspace log4j configuration...");
		try (InputStream is = new FileInputStream(f)) {
			p.load(is);
			for (Entry<Object, Object> entry : p.entrySet()) {
				String value = entry.getValue().toString();
				entry.setValue(value.replaceAll(PATTERN, workspacePath));
			}
		} catch (IOException e) {
			System.err.println("Error while loading properties from file '" + f + "'. Ignoring this file.");
		}
		return p;
	}

}
